package com.jxpanda.starter.wechat;

import com.jxpanda.commons.toolkit.AESKit;
import com.jxpanda.commons.toolkit.HttpKit;
import com.jxpanda.commons.toolkit.json.JsonKit;
import com.jxpanda.starter.wechat.pojo.WechatRequest;
import com.jxpanda.starter.wechat.pojo.WechatResponse;
import com.jxpanda.starter.wechat.pojo.WechatUserData;
import com.jxpanda.starter.wechat.property.WechatProperties;

import javax.annotation.Resource;

/**
 * @author Panda
 */
public class WechatService {

    @Resource
    private WechatProperties wechatProperties;

    @Resource
    private WechatUrlService wechatUrlService;

    public WechatResponse.Session code2Session(String code) {
        return HttpKit.get(wechatUrlService.code2Session(code), WechatResponse.Session.class);
    }

    public WechatResponse.AccessToken accessToken() {
        return HttpKit.get(wechatUrlService.accessToken(), WechatResponse.AccessToken.class);
    }

    public WechatUserData.Info decryptUserInfo(String code, String encryptedData, String iv) {
        return decryptData(code, encryptedData, iv, WechatUserData.Info.class);
    }

    public WechatUserData.Phone decryptUserPhone(String code, String encryptedData, String iv) {
        return decryptData(code, encryptedData, iv, WechatUserData.Phone.class);
    }

    public WechatUserData.Info decryptUserInfo(WechatResponse.Session session, String encryptedData, String iv) {
        return decryptData(session, encryptedData, iv, WechatUserData.Info.class);
    }

    public WechatUserData.Phone decryptUserPhone(WechatResponse.Session session, String encryptedData, String iv) {
        return decryptData(session, encryptedData, iv, WechatUserData.Phone.class);
    }

    private <T extends WechatUserData> T decryptData(String code, String encryptedData, String iv, Class<T> clazz) {
        return decryptData(code2Session(code), encryptedData, iv, clazz);
    }

    private <T extends WechatUserData> T decryptData(WechatResponse.Session session, String encryptedData, String iv, Class<T> clazz) {
        T userData = null;
        if (session.isEffective()) {
            String decryptData = AESKit.decrypt(encryptedData, session.getSessionKey(), iv);
            userData = JsonKit.fromJson(decryptData, clazz);
            if (userData.check(wechatProperties.getApplet().getAppId())) {
                userData.setSession(session);
            }
        }
        return userData;
    }

    public byte[] getQrCodeUnlimited(String scene) {
        String accessToken = accessToken().getAccessToken();
        String url = wechatUrlService.qrCodeUnlimited(accessToken);
        WechatRequest.QRCode qrCode = new WechatRequest.QRCode();
        qrCode.setScene(scene);
        return HttpKit.postForBytes(url, qrCode);
    }

}
